using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace ASPApiDemo.Common;

/// <summary>
/// appsettings.json配置文件的操作类
/// </summary>
public class AppSettings
{
    public static IConfiguration Configuration { get; set; }
    static string contentPath { get; set; }

    public AppSettings(string contentPath)
    {
        string path = "appsettings.json";
        //如果你把配置文件是根据环境变量来分开了，可以这样写
        //path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";
        //如果直接通过配置文件完整路径配置，可以直接读目录里的json文件而不是bin文件夹下的，所以不用修改复制属性
        Configuration = new ConfigurationBuilder()
            .SetBasePath(contentPath)
            .Add(new JsonConfigurationSource
            {
                Path = path,
                Optional = false, //false必要配置文件
                ReloadOnChange = true //json文件更新后自动更新配置
            })
            .Build();
    }
    //也支持直接传入IConfiguration对象配置
    public AppSettings(IConfiguration configuration) => Configuration = configuration;
    //通过节点路径（以冒号分隔）获取配置项
    //configuration["App:Name"];
    public static string GetValue(string sectionsPath) => Configuration[sectionsPath] ?? "未查找到";
    // 将传入的数组拼接成节点路径
    // ["App","Name"] => ["App:Name"]
    public static string app(params string[] sections) =>
        sections.Any() ? Configuration[string.Join(":", sections)] : null;
    // 把配置文件中多层嵌套的配置数据自动转换为内存中的强类型对象集合
    // "Users": {"Active": [{"Id": 1,"Name": "张三"},{"Id": 2,"Name": "李四"}]}=>                                            
    public static List<T> app<T>(params string[] sections)
    {
        List<T> list = new List<T>();
        // 引用 Microsoft.Extensions.Configuration.Binder 包
        Configuration.Bind(string.Join(":", sections), list);
        return list;
    }
}